package filter;
/*
通过用户的cookie是否有session会话记录来判断用户是否登录，如果没有登录则转入登录界面
 */
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CheckLoggingFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//            获取cookie中是否存有session
        //类型向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        System.out.println("CheckLoggingFilter已做拦截。。。。");
        HttpSession session = request.getSession();
        System.out.println(session.getAttribute("logging"));
        try{
            boolean logging = (boolean) session.getAttribute("logging");
            if(logging){
                System.out.println("已经登录！可以放行");
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                response.sendRedirect("loggingCheck.html");
            }
        }catch (Exception throwables){
            response.sendRedirect("loggingCheck.html");
        }
    }

    @Override
    public void destroy() {

    }
}
